import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xin_he/utils/xh_styles.dart';
import 'package:xin_he/utils/xin_he_image.dart';


class XinHeInputWidget extends StatefulWidget {
  XinHeInputWidget(
      this.region,
      this.text,
      this.callback,
      {
        super.key,
        this.isHiddenLine = false,
        this.keyboardType = TextInputType.text,
        this.maxInputLength = 100,
        this.isObscure = false,
        this.isClearAll = true,
        this.fontSize =   16,
        this.hintFontSize =   16,
        this.containerH =   45,

      }
      );
  String region;
  final String text;///内容
  final Function(String) callback;
  bool? isHiddenLine;///是否隐藏横线
  int? maxInputLength;///最大输入长度
  bool? isObscure;///是否加密显示
  bool? isClearAll;///是否显示一键清除
  TextInputType? keyboardType;///键盘类型
  double ? fontSize;
  double ? hintFontSize;
  double ? containerH;



  @override
  State<XinHeInputWidget> createState() => _XinHeInputWidgetState();
}

class _XinHeInputWidgetState extends State<XinHeInputWidget> {

  late bool _isObscure;

  late TextEditingController _textEditingController;
  final FocusNode _focusNode = FocusNode();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _isObscure = widget.isObscure ?? false;
    _textEditingController = TextEditingController();

    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        //有焦点
        setState(() {
        });
      }else{
        //失去焦点
        setState(() {
        });

      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 45,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(width: widget.isHiddenLine! ? 0 :0.5, color: widget.isHiddenLine! ? Colors.transparent : XinHeColor('#E3E3E3'))),
      ),
      child: Container(
        margin: const EdgeInsets.only(bottom: 0),
        // color: Colors.teal,
        height: 45,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            //左侧图标
            widget.region.isNotEmpty?  Container(
              width: 64,
              margin:  const EdgeInsets.only(top: 0,right: 16),
              height: 24,
              alignment: Alignment.centerLeft,
              child: Text(widget.region,style: TextStyle(color: XinHeColor('#222222'),fontSize: widget.fontSize),),
            ) : Container(),

            Expanded(
              child: Container(
                height: 24,
                alignment: Alignment.center,
                child: TextField(
                  style:  TextStyle(
                    fontSize: widget.fontSize,
                    color: XinHeColor('#222222'),
                  ),
                  focusNode: _focusNode,
                  minLines: 1,
                  maxLines: 1,
                  controller: _textEditingController,
                  textAlignVertical: TextAlignVertical.center,
                  textAlign: TextAlign.left,
                  obscureText: _isObscure,
                  decoration: InputDecoration(
                    border: const OutlineInputBorder(borderSide: BorderSide.none),
                    hintText: widget.text,
                    isCollapsed: true,
                    hintStyle:  TextStyle(
                      fontSize: widget.hintFontSize,
                      color: XinHeColor('#979FB5'),
                    ),
                    suffixIcon: Container(
                      width: widget.isObscure!?20+16+21:20,
                      // color: Colors.green,
                      alignment: Alignment.centerRight,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [

                          _focusNode.hasFocus==true && widget.isClearAll! ? GestureDetector(
                              onTap: (){
                                _textEditingController.clear();
                                if(widget.callback!=null){
                                  widget.callback!('');
                                }
                              },
                              child: Image.asset('assets/images/home/input_delete.png',width: 20,height: 20,)):Container(),

                          widget.isObscure! ? Padding(
                            padding: const EdgeInsets.only(left: 16),
                            child: XinHeLoginPwChangeWidget(( bool isSecure){
                              setState(() {
                                _isObscure = isSecure;
                              });
                            }),
                          ):Container(),
                        ],
                      ),
                    ),

                  ),
                  inputFormatters: [

                    //输入规则
                    if(widget.keyboardType == TextInputType.phone) ...[
                      ///仅限输入数字
                      FilteringTextInputFormatter.allow(RegExp( (widget.keyboardType == TextInputType.phone) ? '[0-9]' : '[a-zA-Z]|[0-9]' ??'[^@]')),
                      ///加空格
                      phoneInputFormatter(),
                    ]else if(widget.keyboardType == TextInputType.number)...[
                      FilteringTextInputFormatter.allow(RegExp(  (widget.keyboardType == TextInputType.number) ? '[0-9]' : '[a-zA-Z]|[0-9]' ??'[^@]')),
                    ],


                    // widget.keyboardType == TextInputType.phone
                    //     ?phoneInputFormatter()
                    //     :
                    // FilteringTextInputFormatter.allow(RegExp(  (widget.keyboardType == TextInputType.number) ? '[0-9]' : '[a-zA-Z]|[0-9]' ??'[^@]')),

                    //限制输入长度
                    LengthLimitingTextInputFormatter(widget.maxInputLength! + (widget.keyboardType == TextInputType.phone? 2:0)),
                  ],
                  onChanged: (value) {
                    if(widget.callback!=null){
                      widget.callback!(value);
                    }
                    setState(() {});
                  },
                  keyboardType: widget.keyboardType,

                ),
              ),
            )


          ],
        ),
      ),
    );
  }
}

TextInputFormatter phoneInputFormatter() {
  return TextInputFormatter.withFunction((oldValue, newValue) {
    String text = newValue.text;
    //获取光标左边的文本
    final positionStr = (text.substring(0, newValue.selection.baseOffset)).replaceAll(RegExp(r"\s+\b|\b\s"), "");
    //计算格式化后的光标位置
    int length = positionStr.length;
    var position = 0;
    if (length <= 3) {
      position = length;
    } else if (length <= 7) {
      // 因为前面的字符串里面加了一个空格
      position = length + 1;
    } else if (length <= 11) {
      // 因为前面的字符串里面加了两个空格
      position = length + 2;
    } else {
      // 号码本身为 11 位数字，因多了两个空格，故为 13
      position = 11+2;
    }

    //这里格式化整个输入文本
    text = text.replaceAll(RegExp(r"\s+\b|\b\s"), "");
    var string = "";
    for (int i = 0; i < text.length; i++) {
      // 这里第 4 位，与第 8 位，我们用空格填充
      if (i == 3 || i == 7) {
        if (text[i] != " ") {
          string = string + " ";
        }
      }
      string += text[i];
    }

    return TextEditingValue(
      text: string,
      selection: TextSelection.fromPosition(TextPosition(offset: position, affinity: TextAffinity.upstream)),
    );
  });
}


/// 打开或者关闭密码可见图片
class XinHeLoginPwChangeWidget extends StatefulWidget {
  final Function(bool) hiddenPw; //返回点击打开或者关闭密码可视，true为隐藏
  XinHeLoginPwChangeWidget(this.hiddenPw);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return XinHeLoginPwChangeWidgetState();
  }
}

class XinHeLoginPwChangeWidgetState extends State<XinHeLoginPwChangeWidget> {
  bool pwHidden = true; //默认隐藏密码
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      width: 20,
      height: 20,
      child: GestureDetector(
        onTap: () {
          //点击隐藏或者显示密码
          setState(() {
            pwHidden = !pwHidden;
          });
          widget.hiddenPw(pwHidden);
        },
        child: Container(
          child: Padding(
            padding: const EdgeInsets.all(1),
            child: XinHeAssetImage(pwHidden
                ? "assets/images/login/secture_close_eye.png"
                : "assets/images/login/secture_open_eye.png", fit: BoxFit.scaleDown,width: 20,height: 20,),
          ),
        ),
      ),
    );
  }
}